<?php
/**
 * 应用自定义控制器类
 * 
 * @version $Id: AppController.php 468 2012-10-30 03:26:03Z linsir123 $
 */
class AppController extends Controller 
{
	/**
	 * @var 用户登录信息
	 */
	public $user;
	
	/**
	 * 构造函数
	 */
	public function __construct()
	{
		$this->_checkHost();
		$this->_setCookie();
		
		///
		$this->user = M::user()->data;
		
		///
		AppView::init();
		
		///
		View::assign('user', $this->user);
	}
	
	/**
	 * 输出AJAX操作结果
	 */
	public function ajax($content)
	{
		echo $content;
		///
		exit();
	}
	
	/**
	 * 提示(用于表单提交后进行数据提示)
	 */
	public function tipMsg($content)
	{
		if (empty($content)) 
			return ;
			
		///
		App::registerHook('end', array(& $this, 'tipMsgCallback'), array($content));
	}
	
	/**
	 * 提示返回
	 */
	public function tipMsgCallback($content)
	{
		echo "<script type=\"text/javascript\">$(function() {alert(\"{$content}\");});</script>";
	}
	
	/**
	 * 跳转
	 */
	public function goto301($url)
	{
		lpSystem::h301($url);
		///
		exit();
	}
	
	/**
	 * 找不到页面
	 */
	public function miss($keyword = '')
	{
		if ( ! $this->checkCache('404')) 
			View::assign('keyword', $keyword);
			
		///
		App::end();
	}
	
	/**
	 * 检测是否缓存
	 */
	public function checkCache($template, $cacheId = null)
	{
		if (isset($_GET['clear'])) {
			App::getView()->engine->clearCache($template .'.html', $cacheId);
			
			///
			$url = $_SERVER['REQUEST_URI'];
			$url = substr($url, 0, strpos($url, '?'));
			lpUrl::redirect($url);
		}
		///
		return View::isCached($template, $cacheId);
	}
	
	
	/// 以下为私有方法 ///
	
	
	/**
	 * 检测域名
	 */
	private function _checkHost()
	{
		$serverName = $_SERVER['SERVER_NAME'];
		if ($serverName != '127.0.0.1') {
			if ($serverName != 'www.e35go.com') 
				$this->goto301('http://www.e35go.com'.$_SERVER['REQUEST_URI']);
		}
	}
	
	/**
	 * 设置COOKIE
	 */
	private function _setCookie()
	{
		if ( ! isset($_COOKIE['timestamp']) || ! isset($_COOKIE['sign'])) {
			$conf = App::O('taobaoke.app');
			list($appkey, $secretKey) = $conf;
			
			///
			$timestamp = time() .'000';
			$message = $secretKey .'app_key'. $appkey .'timestamp'. $timestamp . $secretKey;
			$sign = strtoupper(hash_hmac("md5", $message, $secretKey));
			setcookie('timestamp', $timestamp, null, '/');
			setcookie('sign', $sign, null, '/');
		}
	}
}
